<?php
namespace app\devel\model;

use think\Model;
class Term extends Model
{
    static private $default = [
        'flag'            => '',
        'model_id'        => 0,
        'parent_id'       => 0,
        'listorder'       => 0,
        'display_nav'     => 1,
        'name'            => 'default',
        'description'     => '',
        'seo_keywords'    => '',
        'seo_description' => '',
        'seo_title'       => '',
        'status'          => 1,
        'tags_value'      => [],
        'create_time'     => 0,
        'update_time'     => 0,
    ];

    static private $modelList = [];

    public function setModel($modelList)
    {
        self::$modelList = $modelList;
    }

    public function forAddTerm($termArr, $safe=0 , $parentId=0)
    {
        if(!is_array($termArr)) return false;
        foreach($termArr as $termKey => $termInfo){
            $add = $this->initTerm($termInfo, $termKey, $parentId);
            $termId = $this->add($add);
            if($termId === false){
                if($safe=1) return array('Add_Error',$termInfo);
                continue;
            }
            if(!empty($termInfo['child'])){
                $result = $this->forAddTerm($termInfo['child'], $safe, $termId);
                if($result !== true)return $result;
            }
        }
        return true;
    }
    
    static private function initTerm($termInfo, $key, $parentId)
    {
        $time = time();
        $termInfo = array_merge(self::$default, $termInfo);
        if(empty($termInfo['seo_title'])) $termInfo['seo_title']=$termInfo['name'];
        if(empty($termInfo['create_time'])) $termInfo['create_time']=$time;
        if(empty($termInfo['update_time'])) $termInfo['update_time']=$time;
        if(empty($termInfo['flag'])) $termInfo['flag']=is_numeric($key)? $parentId.'_'.$key: $key;
        if(isset($termInfo['model']))
            if(isset(self::$modelList[$termInfo['model']]))
                $termInfo['model_id']=self::$modelList[$termInfo['model']];
        if(is_array($termInfo['tags_value']))
            $termInfo['tags_value'] = json_encode($termInfo['tags_value']);
        $termInfo['parent_id'] = $parentId;
        $termInfo = array_intersect_key($termInfo, self::$default);
        return $termInfo;
    }
}
